package com.polaris.live.popup.party

import android.content.Context
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.AppException
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupJoinMemberBinding
import com.polaris.live.net.liveService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.go_resp.JoinMemberRequest
import com.polaris.live.translation.R.string
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.transformRounded

/**
 *  JoinMemberPopup 加入成员提示
 * @author Created by 天晴 on 2024/3/8 19:18
 * @since 1.0.0
 **/
class JoinMemberPopup(
    context: Context,
    private val mViewModel: BaseViewModel,
    private val roomId: String,
    private val memberPrice: Long,
    private val cover: String,
    private val roomName: String,
    private val onCancel: () -> Unit,
    private val onOk: () -> Unit,
) : CenterPopupView(context) {

    private lateinit var mBinding: PopupJoinMemberBinding
    override fun getImplLayoutId(): Int {
        return R.layout.popup_join_member
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupJoinMemberBinding.bind(popupImplView)
        mBinding.cancel.setOnSingleClickListener {
            dismiss()
        }
        mBinding.cancel.setOnSingleClickListener {
            dismiss()
            onCancel.invoke()
        }
        mBinding.confirm.setOnSingleClickListener {
            if ((UserManager.getUser().account?.coins ?: 0) >= memberPrice) {
                joinMembers(mViewModel, roomId, {
                    onOk.invoke()
                    dismiss()
                }) {
                    if (it.errCode == CommonConst.ErrorCode.SENDGIFT) {
                        GlobalPopupManager.showRechargePopup(context, mViewModel, isNeedBottom = true)
                    } else {
                        ToastGravity.showGravity(it.errorMsg)
                    }
                }
            } else {
                GlobalPopupManager.showRechargePopup(context, mViewModel, isNeedBottom = true)
            }

        }

        mBinding.apply {
            val str = if (memberPrice == 0L) StringUtils.getString(string.free) else "${memberPrice}Diamonds"
            tvMessage.text =
                getColoredString(str, StringUtils.getString(string.join_member_tips, str))
            Glide.with(context)
                .load(ImageUtils.imgPath(cover))
                .transformRounded(6.autoDp)
                .into(roomImg)
            tvRoomName.text = roomName
        }
    }

    private fun getColoredString(memberPrice: String, baseString: String): SpannableString {
        val fullString = String.format(baseString, memberPrice)
        val spannableString = SpannableString(fullString)
        val startIndex = fullString.indexOf(memberPrice)
        val endIndex = startIndex + memberPrice.length
        val color = ContextCompat.getColor(context, R.color.color_ffa100)
        spannableString.setSpan(ForegroundColorSpan(color), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spannableString
    }

    companion object {

        fun show(
            context: Context,
            mViewModel: BaseViewModel,
            roomId: String,
            memberPrice: Long,
            cover: String,
            roomName: String,
            onCancel: () -> Unit,
            onOk: () -> Unit,
        ) {
            XPopup.Builder(context)
                .isViewMode(false)
                .hasShadowBg(true)
                .moveUpToKeyboard(false)
                .isDestroyOnDismiss(true)
                .asCustom(JoinMemberPopup(context, mViewModel, roomId, memberPrice, cover, roomName, onCancel, onOk))
                .show()
        }

        /**
         * 加入成员
         */
        fun joinMembers(mViewModel: BaseViewModel, mRoomId: String, ok: () -> Unit, err: (exc: AppException) -> Unit) {
            mViewModel.requestLoading(
                { liveService.joinMembers(JoinMemberRequest(mRoomId)) }, {
                    ToastGravity.showGravity(StringUtils.getString(string.join_success))
                    ok.invoke()
                },
                {
                    err.invoke(it)
                }, waitTime = 0L
            )
        }
    }
}